package com.tt.plat8.core.manager;

import com.tt.plat8.api.security.IRoleProvider;
import com.tt.plat8.api.user.IFunction;
import com.tt.plat8.api.user.IRoleCode;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: tangtao
 * Date: 14-2-20
 * Time: 下午4:52
 * 角色管理
 */
public class RolesManager {

    private List<IRoleProvider> roleProviders = new ArrayList<IRoleProvider>();

    private Map<String, List<IFunction>> roleFunctionListMap = new HashMap<String, List<IFunction>>();


    private Map<String, String> functionRoleMap = new HashMap<String, String>();

    private static RolesManager install;

    private RolesManager() {

    }

    public synchronized static RolesManager getInstall() {

        if (install == null) {
            install = new RolesManager();
        }
        return install;
    }


    public RolesManager add(IRoleProvider roleProvider) {
        if (roleProvider != null) {
            roleProviders.add(roleProvider);

            List<IRoleCode> roleCodes = roleProvider.getRoleCodes();
            if (roleCodes != null) {
                for (IRoleCode roleCode : roleCodes) {
                    List<IFunction> functionList = roleCode.getFunctions();

                    String strCode = roleCode.getRoleCode();

                    roleFunctionListMap.put(strCode, functionList);
                    if (functionList != null) {
                        for (IFunction function : functionList) {
                            functionRoleMap.put(function.getClassName(), strCode);

                        }
                    }
                }
            }
        }

        return this;
    }


    public RolesManager remove(IRoleProvider roleProvider) {

        if (roleProvider != null) {
            roleProviders.remove(roleProvider);

            List<IRoleCode> roleCodes = roleProvider.getRoleCodes();
            if (roleCodes != null) {
                for (IRoleCode roleCode : roleCodes) {
                    List<IFunction> functionList = roleCode.getFunctions();
                    String strCode = roleCode.getRoleCode();
                    if (roleFunctionListMap.containsKey(strCode)) {
                        roleFunctionListMap.remove(strCode);
                    }

                    if (functionList != null) {
                        for (IFunction function : functionList) {
                            functionRoleMap.remove(function.getClassName());
                        }
                    }

                }
            }
        }
        return this;
    }

    public String getRoleByClassName(String className) {
        return functionRoleMap.get(className);
    }

    public Map<String, String> getRoleMap() {

        return functionRoleMap;
    }
}
